package com.shenyue.nbtownlet.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.design.widget.BottomSheetBehavior;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.google.android.flexbox.FlexboxLayout;
import com.hitomi.glideloader.GlideImageLoader;
import com.hitomi.tilibrary.style.progress.ProgressPieIndicator;
import com.hitomi.tilibrary.transfer.TransferConfig;
import com.hitomi.tilibrary.transfer.Transferee;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;
import com.shenyue.nbtownlet.R;
import com.shenyue.nbtownlet.adapter.LabelListViewAdapter;
import com.shenyue.nbtownlet.base.BaseActivity;
import com.shenyue.nbtownlet.bean.Video;
import com.shenyue.nbtownlet.databinding.ActivitySpotCheckBinding;
import com.shenyue.nbtownlet.databinding.ChoiceOfPersonnelBinding;
import com.shenyue.nbtownlet.databinding.ImagePartItemRemoveBinding;
import com.shenyue.nbtownlet.databinding.SnapShotSheetDialogBinding;
import com.shenyue.nbtownlet.databinding.VideoPartItemRemoveBinding;
import com.shenyue.nbtownlet.event.BaseListener;
import com.shenyue.nbtownlet.location.BDLocationManager;
import com.shenyue.nbtownlet.model.AppContactsModel;
import com.shenyue.nbtownlet.model.AppInsertTaskModel;
import com.shenyue.nbtownlet.model.AppLoginModel;
import com.shenyue.nbtownlet.model.AppModel;
import com.shenyue.nbtownlet.model.AppTaskModel;
import com.shenyue.nbtownlet.model.DefaultModel;
import com.shenyue.nbtownlet.model.FileUploadModel;
import com.shenyue.nbtownlet.util.ActivityUtil;
import com.shenyue.nbtownlet.util.DensityUtil;
import com.shenyue.nbtownlet.util.GlideUtil;
import com.shenyue.nbtownlet.util.GpsUtil;
import com.shenyue.nbtownlet.util.StringUtil;
import com.trycatch.mysnackbar.Prompt;
import com.trycatch.mysnackbar.TSnackbar;
import com.xiao.nicevideoplayer.NiceVideoPlayer;
import com.xiao.nicevideoplayer.NiceVideoPlayerController;
import com.xiao.nicevideoplayer.NiceVideoPlayerManager;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

import cafe.adriel.androidaudioconverter.AndroidAudioConverter;
import cafe.adriel.androidaudioconverter.callback.IConvertCallback;
import cafe.adriel.androidaudioconverter.model.AudioFormat;
import me.nereo.multi_image_selector.MultiImageSelector;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

/**
 * 现场检查1、随手拍0
 */

public class SpotCheckActivity extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener, BaseListener {
    private ActivitySpotCheckBinding binding;
    private Context mContext;
    private Handler mHandler = new Handler();
    private int[] wh;
    private List<String> addImages = new ArrayList<>();
    private List<ImageView> addImageViews = new ArrayList<>();
    private static final int REQUEST_CODE_SELECT = 100;
    private static final int REQUEST_CODE_VIDEO = 201;
    private ArrayList<Video> addVideos = new ArrayList<>();
    // 语音听写UI
    private RecognizerDialog mIatDialog;
    // 录音mp3地址
    private String voice_wav_path;
    private String voice_mp3_path;
    private BottomSheetDialog sheetDialog;
    private LabelListViewAdapter countyListViewAdapter, streetListViewAdapter, iAssessmentListViewAdapter, iiAssessmentListViewAdapter, iiiAssessmentListViewAdapter;
    private SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA);
    private SimpleDateFormat format0 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
    private BDLocationManager bdLocationManager = new BDLocationManager();
    private String type;
    private TSnackbar snackBar;
    private String action_type;
    private SnapShotSheetDialogBinding snapShotSheetDialogBinding;
    private final static int CHOICEPERSONNELAREA = 0x401;
    private List<ChoiceOfPersonnelBinding> choiceOfPersonnelList = new ArrayList<>();
    private ChoiceOfPersonnelBinding selectChoiceOfPersonnelBinding = null;
    private boolean isLoading = false;
    private boolean imageLoading = false;
    private boolean videoLoading = false;
    private boolean voiceLoading = false;
    private int videoPosition = 0;
    private int imagePosition = 0;
    private List<RadioButton> mRadioButtons = new ArrayList<>();

    private JSONObject dataSource;//表单初始数据
    private JSONObject sendData;//表单提交成功数据
    private JSONArray flowSendData;//选择人员之后的数据
    private boolean isUpdate = false;
    private Transferee transferee;
    private JSONObject configData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = DataBindingUtil.setContentView(this, R.layout.activity_spot_check);
        Bundle bundle = getIntent().getExtras();
        type = bundle.getString(DefaultModel.PAGE_DATA_ID);
        String data = bundle.getString(DefaultModel.PAGE_DATA);
        if (!StringUtil.isNull(data)) {
            dataSource = JSON.parseObject(data);
            isUpdate = true;
        }
        setActionBar(true, getString(R.string.tv_spot_check));
        mContext = this;
        transferee = Transferee.getDefault(mContext);

        if ("1".equals(type)) {
            setActionBarTitle(getString(R.string.tv_snapshot));
            binding.scoreView.setVisibility(View.GONE);
            binding.iiiAssessmentView.setVisibility(View.GONE);
        }

        binding.countyPart.setOnClickListener(this);
        binding.streetPart.setOnClickListener(this);
        binding.county.setParentScrollView(binding.scrollView);
        binding.street.setParentScrollView(binding.scrollView);
        binding.iAssessmentPart.setOnClickListener(this);
        binding.iiAssessmentPart.setOnClickListener(this);
        binding.iiiAssessmentPart.setOnClickListener(this);
        binding.iAssessment.setParentScrollView(binding.scrollView);
        binding.iiAssessment.setParentScrollView(binding.scrollView);
        binding.iiiAssessment.setParentScrollView(binding.scrollView);
        binding.btnSaveL.setVisibility(View.GONE);
        binding.btnSendL.setVisibility(View.GONE);
        binding.btnBackL.setVisibility(View.GONE);
        binding.btnCompleteL.setVisibility(View.GONE);
        binding.btnSave.setOnClickListener(this);
        binding.btnSend.setOnClickListener(this);
        binding.btnBack.setOnClickListener(this);
        binding.btnComplete.setOnClickListener(this);

        wh = DensityUtil.getWH(this, 2, 30);
        FlexboxLayout.LayoutParams layoutParams = new FlexboxLayout.LayoutParams(wh[0], wh[1]);
        binding.btnPhoto.setLayoutParams(layoutParams);
        binding.btnPhoto.setOnClickListener(this);
        binding.btnVideo.setLayoutParams(layoutParams);
        binding.btnVideo.setOnClickListener(this);
        binding.btnVoice.setOnClickListener(this);

        binding.score.setItems("0", "1", "2", "3");

        snapShotSheetDialogBinding = DataBindingUtil.inflate(LayoutInflater.from(mContext), R.layout.snap_shot_sheet_dialog, null, false);
        snapShotSheetDialogBinding.btnCancel.setOnClickListener(new SendClickListener());
        snapShotSheetDialogBinding.btnSubmit.setOnClickListener(new SendClickListener());
        sheetDialog = new BottomSheetDialog(this);
        sheetDialog.setContentView(snapShotSheetDialogBinding.getRoot());
        sheetDialog.setCancelable(false);
        sheetDialog.setCanceledOnTouchOutside(false);
        BottomSheetBehavior mDialogBehavior = BottomSheetBehavior.from((View)snapShotSheetDialogBinding.getRoot().getParent());
        if(mDialogBehavior != null) {
            mDialogBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
            mDialogBehavior.setPeekHeight(DensityUtil.dip2px(mContext, 1000));
        }

        /*********讯飞语音输入*******/
        voice_wav_path = ActivityUtil.getVoicePath(mContext) + File.separator + UUID.randomUUID().toString().replace("-", "").substring(24) + ".wav";
        // 初始化听写Dialog，如果只使用有UI听写功能，无需创建SpeechRecognizer
        // 使用UI听写功能，请根据sdk文件目录下的notice.txt,放置布局文件和图片资源
        mIatDialog = new RecognizerDialog(this, mInitListener);
        // 设置听写引擎
        mIatDialog.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);
        // 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
        // 注：AUDIO_FORMAT参数语记需要更新版本才能生效
        mIatDialog.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
        mIatDialog.setParameter(SpeechConstant.ASR_AUDIO_PATH, voice_wav_path);

        setArea();
        setAssessment();

        if (isUpdate) {
            initView();
            JSONObject param = new JSONObject();
            param.put("userID", AppLoginModel.getIdentityId(mContext));
            param.put("flowid", AppModel.FLOWID);
            param.put("formid", AppModel.FORMID);
            param.put("instanceid", StringUtil.dTs(dataSource.getString("ID")));
            AppTaskModel.WaitListDetail(mContext, param, this);
        }else {
            JSONObject param = new JSONObject();
            param.put("userID", AppLoginModel.getIdentityId(mContext));
            param.put("flowid", AppModel.FLOWID);
            param.put("formid", AppModel.FORMID);
            AppTaskModel.WaitListDetail(mContext, param, this);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (!GpsUtil.isOPen(mContext)) {
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
            builder.setTitle("定位服务")
                    .setMessage("定位服务尚未打开，位置获取精度差，是否开启定位服务？")
                    .setPositiveButton("去开启", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            //跳转到设置页面让用户自己手动开启
                            Intent locationIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivity(locationIntent);
                        }
                    }).setNegativeButton("稍候再说", null);
            builder.create().show();
        } else {
            bdLocationManager.start(mContext);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        bdLocationManager.stop();
    }

    private void initView() {
        binding.TADDRESS.setText(StringUtil.getValue(dataSource.getString("TADDRESS")));
        binding.score.setSelectedIndex(Integer.valueOf(dataSource.getString("SCORE")));
        binding.PROBLEM.setText(StringUtil.getValue(dataSource.getString("PROBLEM")));

        binding.REGOINNAME.setText(StringUtil.getValue(dataSource.getString("REGOINNAME")));
        binding.STREETNAME.setText(StringUtil.getValue(dataSource.getString("STREETNAME")));
        binding.ASSESSTYPENAME.setText(StringUtil.getValue(dataSource.getString("ASSESSTYPENAME")));
        binding.ASSESSTASKNAME.setText(StringUtil.getValue(dataSource.getString("ASSESSTASKNAME")));
        binding.ASSESSMENTNAME.setText(StringUtil.getValue(dataSource.getString("ASSESSMENTNAME")));

        String IMAGEADDRESS = StringUtil.getValue(dataSource.getString("IMAGEADDRESS"));
        if (!StringUtil.isNull(IMAGEADDRESS)) {
            String[] array = IMAGEADDRESS.split(",");
            for (int i = 0, j = array.length; i < j; i++) {
                addImages.add(array[i]);
            }
        }

        String MOIVEADDRESS = StringUtil.getValue(dataSource.getString("MOIVEADDRESS"));
        if (!StringUtil.isNull(MOIVEADDRESS)) {
            String[] array = MOIVEADDRESS.split(",");
            for (int i = 0, j = array.length; i < j; i++) {
                addVideos.add(new Video("", "", array[i]));
            }
        }

        resetPhotos();
        resetVideos();
    }

    private void initConfig() {
        List<String> buttons = AppTaskModel.getButtons(mContext, configData);
        if (buttons.contains(AppTaskModel.BTN_SAVE))
            binding.btnSaveL.setVisibility(View.VISIBLE);
        if (buttons.contains(AppTaskModel.BTN_SEND))
            binding.btnSendL.setVisibility(View.VISIBLE);
        if (buttons.contains(AppTaskModel.BTN_BACK))
            binding.btnBackL.setVisibility(View.VISIBLE);
        if (buttons.contains(AppTaskModel.BTN_COMPLETED))
            binding.btnCompleteL.setVisibility(View.VISIBLE);
    }

    private void setArea() {
        countyListViewAdapter = new LabelListViewAdapter(mContext);
        binding.county.setAdapter(countyListViewAdapter);
        binding.county.setOnItemClickListener(this);

        streetListViewAdapter = new LabelListViewAdapter(mContext);
        binding.street.setAdapter(streetListViewAdapter);
        binding.street.setOnItemClickListener(this);
        queryCountyList();
    }

    private void queryCountyList() {
        JSONObject param = new JSONObject();
        param.put("areaid", AppModel.getNingBoAreaID(mContext));
        param.put("areaidByIdentity", AppLoginModel.getAreaId(mContext));
        AppContactsModel.GetNextLevelAreaID(mContext, param, new BaseListener() {
            @Override
            public void success(String val, String action) {
                countyListViewAdapter.clear();
                countyListViewAdapter.addItems(JSON.parseArray(val));
            }

            @Override
            public void error(String error, String action) {
                queryCountyList();
            }
        });
    }

    private void queryStreetList(final String areaid) {
        JSONObject param = new JSONObject();
        param.put("areaid", areaid);
        param.put("areaidByIdentity", AppLoginModel.getAreaId(mContext));
        AppContactsModel.GetNextLevelAreaID(mContext, param, new BaseListener() {
            @Override
            public void success(String val, String action) {
                streetListViewAdapter.clear();
                streetListViewAdapter.addItems(JSON.parseArray(val));
            }

            @Override
            public void error(String error, String action) {
                queryStreetList(areaid);
            }
        });
    }

    private void setAssessment() {
        iAssessmentListViewAdapter = new LabelListViewAdapter(mContext);
        binding.iAssessment.setAdapter(iAssessmentListViewAdapter);
        binding.iAssessment.setOnItemClickListener(this);

        iiAssessmentListViewAdapter = new LabelListViewAdapter(mContext);
        binding.iiAssessment.setAdapter(iiAssessmentListViewAdapter);
        binding.iiAssessment.setOnItemClickListener(this);

        iiiAssessmentListViewAdapter = new LabelListViewAdapter(mContext);
        binding.iiiAssessment.setAdapter(iiiAssessmentListViewAdapter);
        binding.iiiAssessment.setOnItemClickListener(this);
        queryIAssessmentList();
    }

    private void queryIAssessmentList() {
        AppInsertTaskModel.GetAssessType(mContext, null, new BaseListener() {
            @Override
            public void success(String val, String action) {
                iAssessmentListViewAdapter.clear();
                iAssessmentListViewAdapter.addItems(JSON.parseArray(val));
            }

            @Override
            public void error(String error, String action) {
                queryIAssessmentList();
            }
        });
    }

    private void queryIIAssessmentList(final String id) {
        JSONObject param = new JSONObject();
        param.put("type", id);
        AppInsertTaskModel.GetAssessTaskByType(mContext, param, new BaseListener() {
            @Override
            public void success(String val, String action) {
                iiAssessmentListViewAdapter.clear();
                iiAssessmentListViewAdapter.addItems(JSON.parseArray(val));
            }

            @Override
            public void error(String error, String action) {
                queryIIAssessmentList(id);
            }
        });
    }

    private void queryIIIAssessmentList(final String id) {
        JSONObject param = new JSONObject();
        param.put("id", id);
        AppInsertTaskModel.GetAssessMentBYTaskID(mContext, param, new BaseListener() {
            @Override
            public void success(String val, String action) {
                iiiAssessmentListViewAdapter.clear();
                iiiAssessmentListViewAdapter.addItems(JSON.parseArray(val));
            }

            @Override
            public void error(String error, String action) {
                queryIIIAssessmentList(id);
            }
        });
    }

    private View getVideoPartItemRemoveBinding(final Video video) {
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(wh[0], wh[1]);
        VideoPartItemRemoveBinding binding = DataBindingUtil.inflate(LayoutInflater.from(mContext), R.layout.video_part_item_remove, null, false);
        binding.niceVideoPlayer.setPlayerType(NiceVideoPlayer.PLAYER_TYPE_IJK); // or NiceVideoPlayer.PLAYER_NATIVE
        binding.niceVideoPlayer.setUp(video.getVideoUrl(), null);
        NiceVideoPlayerController mController = new NiceVideoPlayerController(mContext);
        mController.setTitle(video.getTitle());
        mController.setImage(video.getImageUrl());
        binding.niceVideoPlayer.setController(mController);
        View view = binding.getRoot();
        view.setLayoutParams(layoutParams);
        binding.btnRemove.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addVideos.remove(video);
                resetVideos();
            }
        });

        return view;
    }

    private View getImagePartItemRemoveBinding(final String url, int id) {
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(wh[0], wh[1]);
        ImagePartItemRemoveBinding root = DataBindingUtil.inflate(LayoutInflater.from(mContext), R.layout.image_part_item_remove, null, false);
        View view = root.getRoot();
        view.setLayoutParams(layoutParams);
        root.btnRemove.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addImages.remove(url);
                resetPhotos();
            }
        });
        root.image.setId(id);
        root.image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TransferConfig config = TransferConfig.build()
                        .setNowThumbnailIndex(v.getId())
                        .setSourceImageList(addImages)
                        .setMissPlaceHolder(R.mipmap.ic_empty_photo)
                        .setOriginImageList(addImageViews)
                        .setProgressIndicator(new ProgressPieIndicator())
                        .setImageLoader(GlideImageLoader.with(mContext.getApplicationContext()))
                        .create();
                transferee.apply(config).show(new Transferee.OnTransfereeStateChangeListener() {
                    @Override
                    public void onShow() {
                        Glide.with(mContext).pauseRequests();
                    }

                    @Override
                    public void onDismiss() {
                        Glide.with(mContext).resumeRequests();
                    }
                });
            }
        });
        addImageViews.add(root.image);
        GlideUtil.loadImgCenterCrop(mContext, url, root.image);

        return view;
    }

    private void resetPhotos() {
        addImageViews.clear();
        View btnPhoto = binding.rectifyImage.getChildAt(binding.rectifyImage.getChildCount() - 1);
        binding.rectifyImage.removeAllViews();
        for (int i = 0, j = addImages.size(); i < j; i++) {
            binding.rectifyImage.addView(getImagePartItemRemoveBinding(addImages.get(i), i));
        }
        binding.rectifyImage.addView(btnPhoto);
    }

    private void resetVideos() {
        View btnVideo = binding.rectifyVideo.getChildAt(binding.rectifyVideo.getChildCount() - 1);
        binding.rectifyVideo.removeAllViews();
        for (int i = 0, j = addVideos.size(); i < j; i++) {
            binding.rectifyVideo.addView(getVideoPartItemRemoveBinding(addVideos.get(i)));
        }
        binding.rectifyVideo.addView(btnVideo);
    }

    private ImageView getImageView(LinearLayout view) {
        return (ImageView) view.getChildAt(1);
    }

    private void changeVisibility(View view, ImageView arrow) {
        int i = view.getVisibility();
        if (i == View.GONE) {
            view.setVisibility(View.VISIBLE);
            arrow.setImageResource(R.mipmap.arrow_up);
        } else {
            view.setVisibility(View.GONE);
            arrow.setImageResource(R.mipmap.arrow_down);
        }
    }

    @Override
    public void onClick(View view) {
        if (isLoading)
            return;
        switch (view.getId()) {
            case R.id.county_part: {//区县
                changeVisibility(binding.county, getImageView((LinearLayout) view));
                break;
            }
            case R.id.street_part: {//街道
                changeVisibility(binding.street, getImageView((LinearLayout) view));
                break;
            }
            case R.id.i_assessment_part: {//考核分类
                changeVisibility(binding.iAssessment, getImageView((LinearLayout) view));
                break;
            }
            case R.id.ii_assessment_part: {//整治任务
                changeVisibility(binding.iiAssessment, getImageView((LinearLayout) view));
                break;
            }
            case R.id.iii_assessment_part: {//考核要求
                changeVisibility(binding.iiiAssessment, getImageView((LinearLayout) view));
                break;
            }
            case R.id.btn_photo:
                doPhoto();
                break;
            case R.id.btn_video:
                doVideo();
                break;
            case R.id.btn_voice:
                doVoice();
                break;
            case R.id.btn_send: {
                action_type = "submit";
                onSave();
                break;
            }
            case R.id.btn_save: {
                action_type = "save";
                onSave();
                break;
            }
        }
    }

    private void doPhoto() {
        MultiImageSelector.create()
                .showCamera(true) // show camera or not. true by default
                .count(9) // max select image size, 9 by default. used width #.multi()
                .multi() // multi mode, default mode;
                .start(this, REQUEST_CODE_SELECT);
    }

    private void doVideo() {
        Intent intent = new Intent(mContext, VideoActivity.class);
        startActivityForResult(intent, REQUEST_CODE_VIDEO);
    }

    private void doVoice() {
        // 显示听写对话框
        mIatDialog.setListener(mRecognizerDialogListener);
        mIatDialog.show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null && requestCode == REQUEST_CODE_SELECT) {
            List<String> images = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
            for (int i = 0, j = images.size(); i < j; i++) {
                String item = images.get(i);
                if (!this.addImages.contains(item))
                    this.addImages.add(item);
            }
            resetPhotos();
        } else if (resultCode == RESULT_OK && data != null && requestCode == REQUEST_CODE_VIDEO) {
            String url = data.getStringExtra("url");
            this.addVideos.add(new Video("", "", url));
            resetVideos();
        } else if (resultCode == RESULT_OK && data != null && requestCode == CHOICEPERSONNELAREA) {
            String val = data.getStringExtra(DefaultModel.PAGE_DATA);
            LabelListViewAdapter listViewAdapter = (LabelListViewAdapter) selectChoiceOfPersonnelBinding.personnelList.getAdapter();
            listViewAdapter.clear();
            listViewAdapter.addItems(JSON.parseArray(val));
        }
    }

    @Override
    public void onBackPressed() {
        if (NiceVideoPlayerManager.instance().onBackPressd()) {
            return;
        }
        doCancel();
    }

    private void printResult(RecognizerResult results, boolean isLast) {
        String result = StringUtil.parseIatResult(results.getResultString());
        int index = binding.PROBLEM.getSelectionStart();//获取光标所在位置
        Editable edit = binding.PROBLEM.getEditableText();
        if (index < 0 || index >= edit.length()) {
            edit.append(result);
        } else {
            edit.insert(index, result);//光标所在位置插入文字
        }
        if (isLast) {
            wavToMap3(voice_wav_path);
        }
    }

    private void wavToMap3(String wav) {
        AndroidAudioConverter.with(this)
                .setFile(new File(wav))
                .setFormat(AudioFormat.MP3)
                .setCallback(new IConvertCallback() {
                    @Override
                    public void onSuccess(File file) {
                        voice_mp3_path = file.getAbsolutePath();
                    }

                    @Override
                    public void onFailure(Exception e) {
                        Log.d("TAG", e.getMessage());
                    }
                })
                .convert();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        bdLocationManager.stop();

        if (!StringUtil.isNull(voice_wav_path))
            new File(voice_wav_path).delete();
        if (!StringUtil.isNull(voice_mp3_path))
            new File(voice_mp3_path).delete();

        if (transferee != null)
            transferee.destroy();
    }

    /**
     * 初始化监听器。
     */
    private InitListener mInitListener = new InitListener() {
        @Override
        public void onInit(int code) {
        }
    };

    /**
     * 听写UI监听器
     */
    private RecognizerDialogListener mRecognizerDialogListener = new RecognizerDialogListener() {
        public void onResult(RecognizerResult results, boolean isLast) {
            printResult(results, isLast);
        }

        /**
         * 识别回调错误.
         */
        public void onError(SpeechError error) {
        }
    };

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (parent == binding.county) {
            JSONArray list = countyListViewAdapter.getItems();
            for (int i = 0, j = list.size(); i < j; i++) {
                JSONObject item = (JSONObject) list.get(i);
                item.put("selected", false);
            }
            final JSONObject item = (JSONObject) list.get(position);
            item.put("selected", true);
            countyListViewAdapter.notifyDataSetChanged();
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    TextView tv = (TextView) binding.countyPart.getChildAt(0);
                    tv.setText(item.getString("NAME"));
                    tv = (TextView) binding.streetPart.getChildAt(0);
                    tv.setText("街道");
                    changeVisibility(binding.county, (ImageView) binding.countyPart.getChildAt(1));
                }
            }, 32);
            queryStreetList(StringUtil.dTs(item.getString("ID")));
        } else if (parent == binding.street) {
            JSONArray list = streetListViewAdapter.getItems();
            for (int i = 0, j = list.size(); i < j; i++) {
                JSONObject item = (JSONObject) list.get(i);
                item.put("selected", false);
            }
            final JSONObject item = (JSONObject) list.get(position);
            item.put("selected", true);
            streetListViewAdapter.notifyDataSetChanged();
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    TextView tv = (TextView) binding.streetPart.getChildAt(0);
                    tv.setText(item.getString("NAME"));
                    changeVisibility(binding.street, (ImageView) binding.streetPart.getChildAt(1));
                }
            }, 32);
        } else if (parent == binding.iAssessment) {
            JSONArray list = iAssessmentListViewAdapter.getItems();
            for (int i = 0, j = list.size(); i < j; i++) {
                JSONObject item = (JSONObject) list.get(i);
                item.put("selected", false);
            }
            final JSONObject item = (JSONObject) list.get(position);
            item.put("selected", true);
            iAssessmentListViewAdapter.notifyDataSetChanged();
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    TextView tv = (TextView) binding.iAssessmentPart.getChildAt(0);
                    tv.setText(item.getString("Name"));
                    tv = (TextView) binding.iiAssessmentPart.getChildAt(0);
                    tv.setText("整治任务");
                    tv = (TextView) binding.iiiAssessmentPart.getChildAt(0);
                    tv.setText("考核要求");
                    changeVisibility(binding.iAssessment, (ImageView) binding.iAssessmentPart.getChildAt(1));
                }
            }, 32);
            queryIIAssessmentList(StringUtil.dTs(item.getString("ID")));
        } else if (parent == binding.iiAssessment) {
            JSONArray list = iiAssessmentListViewAdapter.getItems();
            for (int i = 0, j = list.size(); i < j; i++) {
                JSONObject item = (JSONObject) list.get(i);
                item.put("selected", false);
            }
            final JSONObject item = (JSONObject) list.get(position);
            item.put("selected", true);
            iiAssessmentListViewAdapter.notifyDataSetChanged();
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    TextView tv = (TextView) binding.iiAssessmentPart.getChildAt(0);
                    tv.setText(item.getString("Name"));
                    tv = (TextView) binding.iiiAssessmentPart.getChildAt(0);
                    tv.setText("考核要求");
                    changeVisibility(binding.iiAssessment, (ImageView) binding.iiAssessmentPart.getChildAt(1));
                }
            }, 32);
            if ("0".equals(type))
                queryIIIAssessmentList(StringUtil.dTs(item.getString("ID")));
        } else if (parent == binding.iiiAssessment) {
            JSONArray list = iiiAssessmentListViewAdapter.getItems();
            for (int i = 0, j = list.size(); i < j; i++) {
                JSONObject item = (JSONObject) list.get(i);
                item.put("selected", false);
            }
            final JSONObject item = (JSONObject) list.get(position);
            item.put("selected", true);
            iiiAssessmentListViewAdapter.notifyDataSetChanged();
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    TextView tv = (TextView) binding.iiiAssessmentPart.getChildAt(0);
                    tv.setText(item.getString("REQUIREMENT"));
                    changeVisibility(binding.iiiAssessment, (ImageView) binding.iiiAssessmentPart.getChildAt(1));
                }
            }, 32);
        }
    }

    private void onSave() {
        voiceLoading = false;
        imageLoading = false;
        videoLoading = false;
        videoPosition = 0;
        imagePosition = 0;
        if (!isUpdate)
            dataSource = new JSONObject();
        //dataSource.put("CODE", format.format(new Date()));
        dataSource.put("COMEFROM", "1");
        Location location = bdLocationManager.getLocation();
        if (location != null) {
            dataSource.put("MAPX", StringUtil.getDoubleScale(location.getLongitude(), 8));
            dataSource.put("MAPY", StringUtil.getDoubleScale(location.getLatitude(), 8));
        }else {
            dataSource.put("MAPX", "121.62557100");
            dataSource.put("MAPY", "29.86079100");
        }
        //问题地址
        String REGOINID = null, REGOINNAME = null;
        JSONArray list = countyListViewAdapter.getItems();
        for (int i = 0, j = list.size(); i < j; i++) {
            JSONObject item = (JSONObject) list.get(i);
            if (item.getBooleanValue("selected")) {
                REGOINID = StringUtil.dTs(item.getString("ID"));
                REGOINNAME = StringUtil.getValue(item.getString("NAME"));
                break;
            }
        }
        if (StringUtil.isNull(REGOINID))
            REGOINID = StringUtil.getValue(dataSource.getString("REGOINID"));
        if (StringUtil.isNull(REGOINNAME))
            REGOINNAME = StringUtil.getValue(dataSource.getString("REGOINNAME"));
        if (StringUtil.isNull(REGOINID) || StringUtil.isNull(REGOINNAME)) {
            showMsg("请选择区县");
            return;
        }
        dataSource.put("REGOINID", REGOINID);
        dataSource.put("REGOINNAME", REGOINNAME);
        String STREETID = null, STREETNAME = null;
        list = streetListViewAdapter.getItems();
        for (int i = 0, j = list.size(); i < j; i++) {
            JSONObject item = (JSONObject) list.get(i);
            if (item.getBooleanValue("selected")) {
                STREETID = StringUtil.dTs(item.getString("ID"));
                STREETNAME = StringUtil.getValue(item.getString("NAME"));
                break;
            }
        }
        if (StringUtil.isNull(STREETID))
            STREETID = StringUtil.getValue(dataSource.getString("STREETID"));
        if (StringUtil.isNull(STREETNAME))
            STREETNAME = StringUtil.getValue(dataSource.getString("STREETNAME"));
        if (StringUtil.isNull(STREETID) || StringUtil.isNull(STREETNAME)) {
            showMsg("请选择街道");
            return;
        }
        dataSource.put("STREETID", STREETID);
        dataSource.put("STREETNAME", STREETNAME);
        String TADDRESS = binding.TADDRESS.getText().toString();
        if (StringUtil.isNull(TADDRESS)) {
            showMsg("请输入问题街道地址");
            return;
        }
        String ASSESSTYPEID = null, ASSESSTYPENAME = null;
        list = iAssessmentListViewAdapter.getItems();
        for (int i = 0, j = list.size(); i < j; i++) {
            JSONObject item = (JSONObject) list.get(i);
            if (item.getBooleanValue("selected")) {
                ASSESSTYPEID = StringUtil.dTs(item.getString("ID"));
                ASSESSTYPENAME = StringUtil.getValue(item.getString("Name"));
                break;
            }
        }
        if (StringUtil.isNull(ASSESSTYPEID))
            ASSESSTYPEID = StringUtil.getValue(dataSource.getString("ASSESSTYPEID"));
        if (StringUtil.isNull(ASSESSTYPENAME))
            ASSESSTYPENAME = StringUtil.getValue(dataSource.getString("ASSESSTYPENAME"));
        if (StringUtil.isNull(ASSESSTYPEID) || StringUtil.isNull(ASSESSTYPENAME)) {
            showMsg("请选择考核分类");
            return;
        }
        dataSource.put("ASSESSTYPEID", ASSESSTYPEID);
        dataSource.put("ASSESSTYPENAME", ASSESSTYPENAME);
        String ASSESSTASKID = null, ASSESSTASKNAME = null, KeyWord = null;
        list = iiAssessmentListViewAdapter.getItems();
        for (int i = 0, j = list.size(); i < j; i++) {
            JSONObject item = (JSONObject) list.get(i);
            if (item.getBooleanValue("selected")) {
                ASSESSTASKID = StringUtil.dTs(item.getString("ID"));
                ASSESSTASKNAME = StringUtil.getValue(item.getString("Name"));
                KeyWord = StringUtil.getValue(item.getString("KeyWord"));
                break;
            }
        }
        if (StringUtil.isNull(ASSESSTASKID))
            ASSESSTASKID = StringUtil.getValue(dataSource.getString("ASSESSTASKID"));
        if (StringUtil.isNull(ASSESSTASKNAME))
            ASSESSTASKNAME = StringUtil.getValue(dataSource.getString("ASSESSTASKNAME"));
        if (StringUtil.isNull(ASSESSTASKID) || StringUtil.isNull(ASSESSTASKNAME)) {
            showMsg("请选择整治任务");
            return;
        }
        dataSource.put("ASSESSTASKID", ASSESSTASKID);
        dataSource.put("ASSESSTASKNAME", ASSESSTASKNAME);
        if ("0".equals(type)) {
            String ASSESSMENTID = null, ASSESSMENTNAME = null;
            list = iiiAssessmentListViewAdapter.getItems();
            for (int i = 0, j = list.size(); i < j; i++) {
                JSONObject item = (JSONObject) list.get(i);
                if (item.getBooleanValue("selected")) {
                    ASSESSMENTID = StringUtil.dTs(item.getString("ID"));
                    ASSESSMENTNAME = StringUtil.getValue(item.getString("REQUIREMENT"));
                    break;
                }
            }
            if (StringUtil.isNull(ASSESSMENTID))
                ASSESSMENTID = StringUtil.getValue(dataSource.getString("ASSESSMENTID"));
            if (StringUtil.isNull(ASSESSMENTNAME))
                ASSESSMENTNAME = StringUtil.getValue(dataSource.getString("ASSESSMENTNAME"));
            if (StringUtil.isNull(ASSESSMENTID) || StringUtil.isNull(ASSESSMENTNAME)) {
                showMsg("请选择考核要求");
                return;
            }
            dataSource.put("ASSESSMENTID ", ASSESSMENTID);
            dataSource.put("ASSESSMENTNAME", ASSESSMENTNAME);
        } else {
            dataSource.put("ASSESSMENTID ", "45");
            dataSource.put("ASSESSMENTNAME", "邱隘镇水体整治");
        }

        dataSource.put("MENTTYPE", type);
        dataSource.put("WORKTYPE", type);
        dataSource.put("STATUS", "0");
        if ("1".equals(type)) {
            dataSource.put("SCORE", "0");
        } else {
            dataSource.put("SCORE", StringUtil.getValue(binding.score.getText()));
        }
        dataSource.put("CREATORID", AppLoginModel.getUserId(mContext));
        dataSource.put("CREATORIDENTITY", AppLoginModel.getIdentityId(mContext));
        dataSource.put("CREATORNAME", AppLoginModel.getUserName(mContext));
        dataSource.put("CREATETIME", format0.format(new Date()));
        dataSource.put("EDITID", AppLoginModel.getUserId(mContext));
        dataSource.put("EDITIDENTITY", AppLoginModel.getIdentityId(mContext));
        dataSource.put("EDITNAME", AppLoginModel.getUserName(mContext));
        dataSource.put("EDITTIME", format0.format(new Date()));
        dataSource.put("USERID", AppLoginModel.getUserId(mContext));
        dataSource.put("USERIDENTITY", AppLoginModel.getIdentityId(mContext));
        dataSource.put("IMAGEADDRESS", "");//问题图片路径
        dataSource.put("MOIVEADDRESS", "");//问题视频路径
        dataSource.put("VOICEPROBLEM", "");//音频文件路径
        dataSource.put("TADDRESS", TADDRESS);
        dataSource.put("PROBLEM", binding.PROBLEM.getText().toString().trim());
        if (!StringUtil.isNull(KeyWord)) {
            dataSource.put("TITILE", dataSource.getString("STREETNAME") + KeyWord);
        }

        isLoading = true;
        snackBar = showTSnackbar("正在提交信息..., 请稍候");
        if (voice_mp3_path != null) {
            voiceLoading = true;
            FileUploadModel.upload(mContext, voice_mp3_path, false, this);
            return;
        }

        if (!addImages.isEmpty()) {
            imageLoading = true;
            FileUploadModel.upload(mContext, addImages.get(imagePosition), true, this);
            return;
        }

        if (!addVideos.isEmpty()) {
            videoLoading = true;
            FileUploadModel.upload(mContext, addVideos.get(videoPosition).getVideoUrl(), false, this);
            return;
        }
        if (voiceLoading || imageLoading || videoLoading)
            return;

        if (isUpdate)
            AppInsertTaskModel.UpdatessData(mContext, dataSource, this);
        else
            AppInsertTaskModel.InsertssData(mContext, dataSource, this);
    }

    @Override
    public void success(String val, String action) {
        if (AppTaskModel.WAITLIST_DETAIL_ACTION.equals(action)) {
            configData = JSON.parseObject(val);
            initConfig();
        } else if (AppInsertTaskModel.INSERTSSDATA_ACTION.equals(action)) {
            JSONObject data = JSON.parseObject(val);
            if ("true".equals(data.getString("IsSuccess"))) {
                sendData = data;
                if ("save".equals(action_type)) {//调用流程 Execute方法
                    hideTSnackbar(snackBar, "信息保存成功");
                    AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                    builder.setTitle("信息提交成功");
                    builder.setMessage("信息保存成功");
                    builder.setCancelable(false);
                    builder.setPositiveButton("我知道了", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            setResult(RESULT_OK);
                            finish();
                        }
                    });
                    builder.show();
                } else if ("submit".equals(action_type)) {//调用流程 FlowSend方法
                    FlowSend(data);
                }
            } else {
                isLoading = false;
                hideTSnackbar(snackBar, "信息提交失败，相应参数有错", Prompt.WARNING);
            }
        } else if (AppInsertTaskModel.UPDATESSDATA_ACTION.equals(action)) {
            JSONObject data = JSON.parseObject(val);
            if ("true".equals(data.getString("IsSuccess"))) {
                sendData = data;
                if ("save".equals(action_type)) {//调用流程 Execute方法
                    hideTSnackbar(snackBar, "信息保存成功");
                    AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                    builder.setTitle("信息提交成功");
                    builder.setMessage("信息保存成功");
                    builder.setCancelable(false);
                    builder.setPositiveButton("我知道了", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            setResult(RESULT_OK);
                            finish();
                        }
                    });
                    builder.show();
                } else if ("submit".equals(action_type)) {//调用流程 FlowSend方法
                    FlowSend(data);
                }
            } else {
                isLoading = false;
                hideTSnackbar(snackBar, "信息提交失败，相应参数有错", Prompt.WARNING);
            }
        } else if (AppTaskModel.WAITLIST_EXECUTE_ACTION.equals(action)) {
            JSONObject data = JSON.parseObject(val);
            if ("true".equals(data.getString("IsSuccess"))) {
                if ("submit".equals(action_type)) {
                    JSONObject param = new JSONObject();
                    param.put("workstatus", "1");
                    param.put("id", StringUtil.dTs(sendData.getString("ID")));
                    AppInsertTaskModel.Getchangeformstatus(mContext, param, null);
                }
                hideTSnackbar(snackBar, data.getString("Messages"));
                AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                builder.setTitle("信息提交成功");
                builder.setMessage(data.getString("Messages"));
                builder.setCancelable(false);
                builder.setPositiveButton("我知道了", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        setResult(RESULT_OK);
                        finish();
                    }
                });
                builder.show();
            } else {
                isLoading = false;
                hideTSnackbar(snackBar, "信息提交失败，相应参数有错", Prompt.WARNING);
            }
        } else if (AppTaskModel.WAITLIST_FLOWSEND_ACTION.equals(action)) {
            hideTSnackbar(snackBar, "请选择流程对应的人员");
            mRadioButtons.clear();
            flowSendData = JSON.parseArray(val);
            choiceOfPersonnelList.clear();
            snapShotSheetDialogBinding.flowSend.removeAllViews();
            for (int i = 0; i < flowSendData.size(); i++) {
                ChoiceOfPersonnelBinding root = getChoiceOfPersonnelBinding(flowSendData.getJSONObject(i));
                choiceOfPersonnelList.add(root);
                snapShotSheetDialogBinding.flowSend.addView(root.getRoot());
            }
            sheetDialog.show();
        } else if (FileUploadModel.SMALLTOWN_XCZFILEUPLOAD_SAVEFILE_ACTION.equals(action)) {
            if (voiceLoading) {
                JSONObject data = JSON.parseObject(val);
                dataSource.put("VOICEPROBLEM", data.getString("FullUrl"));
                voiceLoading = false;
                if (!addImages.isEmpty()) {
                    imageLoading = true;
                    FileUploadModel.upload(mContext, addImages.get(imagePosition), true, this);
                    return;
                }
                if (!addVideos.isEmpty()) {
                    videoLoading = true;
                    FileUploadModel.upload(mContext, addVideos.get(videoPosition).getVideoUrl(), false, this);
                    return;
                }
                if (isUpdate)
                    AppInsertTaskModel.UpdatessData(mContext, dataSource, this);
                else
                    AppInsertTaskModel.InsertssData(mContext, dataSource, this);
            } else if (imageLoading) {
                JSONObject data = JSON.parseObject(val);
                String IMAGEADDRESS = dataSource.getString("IMAGEADDRESS");
                StringBuilder sb = new StringBuilder();
                if (!StringUtil.isNull(IMAGEADDRESS))
                    sb.append(IMAGEADDRESS).append(",").append(data.getString("FullUrl")).append(",");
                else
                    sb.append(data.getString("FullUrl")).append(",");
                if (sb.lastIndexOf(",") != -1)
                    sb.deleteCharAt(sb.lastIndexOf(","));
                dataSource.put("IMAGEADDRESS", sb.toString());

                if ((imagePosition + 1) >= addImages.size()) {
                    imageLoading = false;
                    if (!addVideos.isEmpty()) {
                        videoLoading = true;
                        FileUploadModel.upload(mContext, addVideos.get(videoPosition).getVideoUrl(), false, this);
                        return;
                    }
                    if (isUpdate)
                        AppInsertTaskModel.UpdatessData(mContext, dataSource, this);
                    else
                        AppInsertTaskModel.InsertssData(mContext, dataSource, this);
                } else {
                    imagePosition++;
                    FileUploadModel.upload(mContext, addImages.get(imagePosition), true, this);
                }
            } else if (videoLoading) {
                JSONObject data = JSON.parseObject(val);
                String MOIVEADDRESS = dataSource.getString("MOIVEADDRESS");
                StringBuilder sb = new StringBuilder();
                if (!StringUtil.isNull(MOIVEADDRESS))
                    sb.append(MOIVEADDRESS).append(",").append(data.getString("FullUrl")).append(",");
                else
                    sb.append(data.getString("FullUrl")).append(",");
                if (sb.lastIndexOf(",") != -1)
                    sb.deleteCharAt(sb.lastIndexOf(","));
                dataSource.put("MOIVEADDRESS", sb.toString());

                if ((videoPosition + 1) >= addVideos.size()) {
                    videoLoading = false;
                    if (isUpdate)
                        AppInsertTaskModel.UpdatessData(mContext, dataSource, this);
                    else
                        AppInsertTaskModel.InsertssData(mContext, dataSource, this);
                } else {
                    videoPosition++;
                    FileUploadModel.upload(mContext, addVideos.get(videoPosition).getVideoUrl(), false, this);
                }
            }
        }
    }

    @Override
    public void error(String error, String action) {
        if (FileUploadModel.SMALLTOWN_XCZFILEUPLOAD_SAVEFILE_ACTION.equals(action)) {
            voiceLoading = false;
            imageLoading = false;
            videoLoading = false;
            FileUploadModel.stop();
            if (isUpdate)
                AppInsertTaskModel.UpdatessData(mContext, dataSource, this);
            else
                AppInsertTaskModel.InsertssData(mContext, dataSource, this);
            return;
        }
        isLoading = false;
        hideTSnackbar(snackBar, error, Prompt.WARNING);
    }

    private void Execute(JSONObject data, JSONArray steps, String comment) {
        JSONObject param = new JSONObject();
        param.put("flowid", configData.getString("flowid"));
        param.put("instanceid", StringUtil.dTs(data.getString("ID")));
        param.put("stepid", configData.getString("stepid"));
        param.put("taskid", configData.getString("taskid"));
        param.put("userID", AppLoginModel.getIdentityId(mContext));
        param.put("Formid", AppModel.FORMID);
        param.put("issign", configData.getString("issign"));
        param.put("groupid", AppModel.GROUPID);
        param.put("ctype", "");
        param.put("comment", comment);
        param.put("taskname", dataSource.getString("TITILE"));
        param.put("taskcode", data.getString("Code"));
        JSONObject params = new JSONObject();
        params.put("type", action_type);
        params.put("steps", steps == null ? "" : steps);
        param.put("params1", params.toString());
        AppTaskModel.WaitListExecute(mContext, param, this);
    }

    private void FlowSend(JSONObject data) {
        JSONObject param = new JSONObject();
        param.put("areaid", dataSource.getString("STREETID"));
        param.put("instanceid", StringUtil.dTs(data.getString("ID")));
        param.put("stepid", configData.getString("stepid"));
        param.put("taskid", configData.getString("taskid"));
        param.put("userID", AppLoginModel.getIdentityId(mContext));
        param.put("tasktype", configData.getString("signType"));
        param.put("flowid", configData.getString("flowid"));
        param.put("groupid", AppModel.GROUPID);
        AppTaskModel.WaitListFlowSend(mContext, param, this);
    }

    private ChoiceOfPersonnelBinding getChoiceOfPersonnelBinding(final JSONObject data) {
        final ChoiceOfPersonnelBinding root = DataBindingUtil.inflate(LayoutInflater.from(mContext), R.layout.choice_of_personnel, null, false);
        root.radio.setText(StringUtil.isNull(data.getString("stepname")) ? data.getString("name") : data.getString("stepname"));
        root.radio.setChecked("1".equals(data.getString("ischeck")));
        root.btnArea.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectChoiceOfPersonnelBinding = root;
                Bundle bundle = new Bundle();
                bundle.putString(DefaultModel.PAGE_DATA, "0");
                bundle.putString("selectRang", data.getString("selectRang"));
                bundle.putString("Isfilt", data.getString("isfilt"));
                bundle.putString("STREETID", dataSource.getString("STREETID"));
                toActivityForResult(ChoicePersonnelActivity.class, bundle, CHOICEPERSONNELAREA);
            }
        });
        root.radio.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int i = 0; i < mRadioButtons.size(); i++) {
                    RadioButton rad = mRadioButtons.get(i);
                    if(rad == root.radio){
                        rad.setChecked(true);
                    }else{
                        rad.setChecked(false);
                    }
                }
            }
        });
        mRadioButtons.add(root.radio);
        LabelListViewAdapter listViewAdapter = new LabelListViewAdapter(mContext);
        root.personnelList.setAdapter(listViewAdapter);
        root.personnelList.setParentScrollView(snapShotSheetDialogBinding.scrollView);
        View view = root.getRoot();
        view.setTag(data.toString());
        return root;
    }

    private class SendClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_cancel: {//取消
                    sheetDialog.hide();
                    isLoading = false;
                    break;
                }
                case R.id.btn_submit: {//提交
                    //步骤及人员信息字典数组
                    JSONArray array = new JSONArray();
                    for (int i = 0, j = flowSendData.size(); i < j; i++) {
                        final JSONObject flow = flowSendData.getJSONObject(i);
                        ChoiceOfPersonnelBinding root = choiceOfPersonnelList.get(i);
                        if(!root.radio.isChecked())
                            continue;
                        LabelListViewAdapter listViewAdapter = (LabelListViewAdapter) root.personnelList.getAdapter();
                        JSONArray items = listViewAdapter.getItems();
                        final StringBuilder sb = new StringBuilder();
                        for (int k = 0, h = items.size(); k < h; k++) {
                            JSONObject item = items.getJSONObject(k);
                            sb.append(item.getString("ID")).append(",");
                        }
                        if (sb.lastIndexOf(",") != -1)
                            sb.deleteCharAt(sb.lastIndexOf(","));
                        if(StringUtil.isNull(sb.toString()) && root.btnArea.getVisibility() == View.VISIBLE){
                            Toast.makeText(mContext, "请选择流程步骤对应的人员", Toast.LENGTH_LONG).show();
                            return;
                        }
                        array.add(new JSONObject() {{
                            put("id", flow.getString("stepid"));
                            put("member", sb.toString());
                        }});
                    }
                    if (array.isEmpty()) {
                        Toast.makeText(mContext, "请选择人员", Toast.LENGTH_LONG).show();
                        return;
                    }
                    sheetDialog.hide();
                    snackBar = showTSnackbar("正在提交数据..., 请稍候");
                    Execute(sendData, array, snapShotSheetDialogBinding.comment.getText().toString().trim());
                    break;
                }
            }
        }
    }

    private void doCancel() {
        String msg = "数据尚未提交，您确定要退出吗？";
        if (isLoading)
            msg = "数据正在提交，您确定要退出吗？";
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("温馨提示")
                .setMessage(msg)
                .setPositiveButton("点错了", null)
                .setNegativeButton("退出", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        FileUploadModel.stop();
                        dialogInterface.dismiss();
                        finish();
                    }
                });
        builder.create().show();
    }
}
